const path = require("path");
const fs = require("fs");
const prettier = require("prettier");
const readline = require("readline");
const { test, dirU } = require("./common");
const os = require("os");
const replaceFileL18n = async (
  fullPath,
  newPath,
  lang,
  context,
  isSetup = false
) => {
  const extname = path.extname(fullPath);
  let ContentLine = "";
  let fileContent = "";
  const langObj = {};
  const code = await prettier.format(lang, {
    parser: "json",
  });
  lang = JSON.parse(code);
  for (let cs_key in lang) {
    for (let key in lang[cs_key]) {
      langObj[lang[cs_key][key]] = cs_key + "." + key;
    }
  }
  return new Promise((resolve, reject) => {
    const key = fullPath
      .replace(context.projectPath, "")
      .replace(".vue", "")
      .split("/")
      .map((key) =>
        key
          .split("-")
          .map((str, index) =>
            index == 0 ? str : str.charAt(0).toUpperCase() + str.slice(1)
          )
          .join("")
      )
      .filter((item) => item)
      .join(".");
    const pagePath = `pages.${key}`;

    fs.writeFileSync(newPath, "", {
      flag: "a+",
    });
    let isNote = false;
    let fsWrite = fs.createWriteStream(newPath);
    let rl = readline.createInterface({
      input: fs.createReadStream(fullPath),
      output: fsWrite,
    });
    let isTemplate = false;
    let templateCount = 0;
    rl.on("line", (line) => {
      let content = isNote ? "" : line;
      ContentLine = line;
      if (line.includes("/*")) {
        isNote = true;
        content = line.slice(0, line.indexOf("/*"));
      }
      if (line.includes("*/")) {
        if (isNote) {
          isNote = false;
          content = line.slice(line.indexOf("*/") + 2);
        }
      }
      if (line.includes("<!--")) {
        isNote = true;
        content = line.slice(0, line.indexOf("<!--"));
      }
      if (line.includes("-->")) {
        if (isNote) {
          isNote = false;
          content = line.slice(line.indexOf("-->") + 3);
        }
      }
      if (line.includes("//")) content = line.slice(0, line.indexOf("//"));

      if ([".vue"].includes(extname)) {
        if (line.indexOf("<template") > -1) {
          if (!isTemplate) {
            isTemplate = true;
          }
          ++templateCount;
        }

        if (line.indexOf("</template>") > -1) {
          --templateCount;
          if (templateCount === 0) isTemplate = false;
        }
      }
      let str = content.match(test);
      while (str) {
        if (str) {
          str = str[0];
          let otherStr = "";
          if (content.indexOf("'" + str) > -1) {
            let contentArr = content.split(str);
            otherStr = contentArr[1]
              ? contentArr[1].slice(0, contentArr[1].indexOf("'"))
              : "";
          }
          if (content.indexOf('"' + str) > -1) {
            let contentArr = content.split(str);
            otherStr = contentArr[1]
              ? contentArr[1].slice(0, contentArr[1].indexOf('"'))
              : "";
          }
          if (content.indexOf(">" + str) > -1) {
            let contentArr = content.split(str);
            otherStr = contentArr[1]
              ? contentArr[1].slice(0, contentArr[1].indexOf("<"))
              : "";
          }
          if (content.indexOf(str + '"') > -1) {
            let contentArr = content.split(str);
            let reverseStr = contentArr[0].split("").reverse();
            str =
              reverseStr.splice(0, reverseStr.indexOf('"')).reverse().join("") +
              str;
          } else {
            str += otherStr; // .replace(/{{(.*)}}/g, '')
          }
        }

        str = str.trim();
        str = str.replace(/{{(.*)}}$/g, "");
        content =
          content.slice(0, content.indexOf(str)) +
          content.slice(content.indexOf(str) + str.length);

        if (langObj[str]) {
          // if(!ContentLine.match(test)) return
          if ([".vue"].includes(extname)) {
            let props = [];
            if (isTemplate) {
              props =
                ContentLine.match(/([^=\s]+="[^"]+")|([^=\s]+='[^']+')/g) || [];
              props.forEach((item) => {
                if (
                  item.indexOf(`="${str}"`) > -1 ||
                  item.indexOf(`='${str}'`) > -1
                ) {
                  let LangItem =
                    ":" + item.replace(str, `$tl('${langObj[str]}')`);
                  ContentLine = ContentLine.replace(item, LangItem);
                }
              });
            }
            props = ContentLine.match(/(?<=\`)([^\`]*)(?=\`)/g) || [];
            props.forEach((item) => {
              if (item.indexOf(`${str}`) > -1) {
                let LangItem = item.replace(
                  str,
                  "${" + `$tl('${langObj[str]}')` + "}"
                );
                ContentLine = ContentLine.replace(item, LangItem);
              }
            });
            if (
              ContentLine.includes(`"${str}"`) ||
              ContentLine.includes(`'${str}'`)
            ) {
              ContentLine = ContentLine.replace(
                `'${str}'`,
                isTemplate
                  ? `$tl('${langObj[str]}')`
                  : isSetup
                    ? `$tl('${langObj[str]}')`
                    : `this.$tl('${langObj[str]}')`
              );
              ContentLine = ContentLine.replace(
                `"${str}"`,
                isTemplate
                  ? `"{{$tl('${langObj[str]}')}}"`
                  : isSetup
                    ? `$tl('${langObj[str]}')`
                    : `this.$tl('${langObj[str]}')`
              );
            } else {
              ContentLine = ContentLine.replace(
                `${str}`,
                isTemplate
                  ? `{{$tl('${langObj[str]}')}}`
                  : isSetup
                    ? `$tl('${langObj[str]}')`
                    : `this.$tl('${langObj[str]}')`
              );
            }
          }
          if ([".js"].includes(extname)) {
            ContentLine = ContentLine.replace(
              `'${str}'`,
              `i18n.t('${langObj[str]}')`
            );
            ContentLine = ContentLine.replace(
              `"${str}"`,
              `i18n.t('${langObj[str]}')`
            );
          }
        } else {
          console.log(`error 解析失败 key:${str} val:${langObj[str]}`);
        }
        str = content.match(test);
      }
      if (ContentLine.includes("methods: {")) {
        const key = fullPath
          .replace(context.projectPath, "")
          .replace(".vue", "")
          .split("/")
          .map((key) =>
            key
              .split("-")
              .map((str, index) =>
                index == 0 ? str : str.charAt(0).toUpperCase() + str.slice(1)
              )
              .join("")
          )
          .join(".");
        ContentLine = ContentLine.replace(
          "methods: {",
          `methods: {
      $tl(key, ...args) {
        return this.$t(\`${pagePath}.$\{key}\`, ...args)
      },`
        );
      }
      fileContent += ContentLine + os.EOL;
      fsWrite.write(ContentLine + os.EOL);
    });
    rl.on("close", () => {
      resolve({
        pagePath: pagePath,
      });
    });
  });
};

module.exports = replaceFileL18n;
